//
//  XKNetworkTool.swift
//  XK2WeiBo
//
//  Created by 陈肖坤 on 2017/7/3.
//  Copyright © 2017年 陈肖坤. All rights reserved.
//

import UIKit
import AFNetworking
enum MethodType:String {
    case GET = "GET"
    case POST = "POST"
}

class XKNetworkTool: AFHTTPSessionManager {
    //全局访问点
    static let sharedTools:XKNetworkTool = {
        // 实例化对象
        let instance = XKNetworkTool()
        
        // 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 返回对象
        return instance
        
    }()
    
    // 给我们成功的闭包和失败的闭包格式起别名
    typealias SuccessClosure = (_ response: AnyObject?)->()
    typealias FailureClosure = (_ error: NSError)->()
    //
    /**
     请求数据方法
     
     - parameter method:     方式
     - parameter urlString:  url
     - parameter parameters: 参数
     - parameter success:    成功
     - parameter failure:    失败
     */
    func request(_ method:MethodType, urlString: String, parameters: AnyObject?, success: @escaping SuccessClosure, failure: @escaping FailureClosure){
        // GET 请求
        if method == .GET {
            self.get(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(String(describing: res) as AnyObject)
            }, failure: { (_, err) -> Void in
                failure((String(describing: err) as AnyObject) as! NSError)
                
            })
        }else {
            // POST 请求
            self.post(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(String(describing: res) as AnyObject)
            }, failure: { (_, err) -> Void in
                failure((String(describing: err) as AnyObject) as! NSError)
                
            })
        }
    }
}

extension XKNetworkTool {
    // 请求token
    func oauthLoadUserAccount(_ code: String, success: @escaping SuccessClosure, failure: @escaping FailureClosure){
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id":APP_KEY,
            "client_secret":APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
        ]
        
        self.request(MethodType.POST, urlString: urlString, parameters: params as AnyObject, success: success, failure: failure)
   }
}


